package com.sen.uaa.config;

import com.sen.uaa.granter.CaGranter;
import com.sen.uaa.granter.ImgCodeGranter;
import com.sen.uaa.service.CustomTokenServices;
import com.sen.uaa.service.IValidateCodeService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * token授权模式配置类
 *
 * @author esjiang
 */
@Configuration
public class TokenGranterConfig {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private TokenStore tokenStore;

    @Resource
    private IValidateCodeService validateCodeService;

    private TokenGranter tokenGranter;

    @Resource
    private DataSource dataSource;

    /***
     * 定制token信息
     */
    @Resource
    private TokenEnhancerConfig tokenEnhancerConfig ;

    @Resource
    private UserDetailsService userDetailsService;

    @Bean
    public ClientDetailsService clientDetailsService(){
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 授权模式
     */
    @Bean
    public TokenGranter tokenGranter() {
        if (tokenGranter == null) {
            tokenGranter = new TokenGranter() {
                private CompositeTokenGranter delegate;

                @Override
                public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
                    if (delegate == null) {
                        delegate = new CompositeTokenGranter(getAllTokenGranters());
                    }
                    return delegate.grant(grantType, tokenRequest);
                }
            };
        }
        return tokenGranter;
    }

    @Bean
    public DefaultTokenServices defaultTokenServices(){
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain() ;
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancerConfig));
        DefaultTokenServices defaultTokenServices =new CustomTokenServices(true);
        defaultTokenServices.setTokenStore(tokenStore);
        defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);
        defaultTokenServices.setClientDetailsService(clientDetailsService());
        addUserDetailsService(defaultTokenServices,userDetailsService);
        return defaultTokenServices;
    }

    /**
     * 所有授权模式：4种模式 + 自定义的模式
     */
    private List<TokenGranter> getAllTokenGranters() {
        AuthorizationServerTokenServices tokenServices = defaultTokenServices();
        OAuth2RequestFactory requestFactory = requestFactory();
        List<TokenGranter> tokenGranters = getDefaultTokenGranters(tokenServices, requestFactory);
        if (authenticationManager != null) {
            tokenGranters.add(new ImgCodeGranter(authenticationManager, tokenServices, clientDetailsService(), requestFactory, validateCodeService));
            tokenGranters.add(new CaGranter(tokenServices,clientDetailsService(),requestFactory,authenticationManager)) ;
        }
        return tokenGranters;
    }

    /**
     * 默认的授权模式
     */
    private List<TokenGranter> getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
            , OAuth2RequestFactory requestFactory) {
        List<TokenGranter> tokenGranters = new ArrayList<>();
        tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService(), requestFactory));
        tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsService(), requestFactory));
        tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService(), requestFactory));
        if (authenticationManager != null) {
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService(), requestFactory));
        }
        return tokenGranters;
    }


    private OAuth2RequestFactory requestFactory() {
        return new DefaultOAuth2RequestFactory(clientDetailsService());
    }


    private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
        if (userDetailsService != null) {
            PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
            provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsService));
            tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
        }
    }
}
